package net.fonline.apps;

import javax.microedition.lcdui.Graphics;

/**
 * This is a list to manage all monsters/minions currently running over the map.
 * @author Michael
 */
class MonsterList {

    private Monster root = null;
    private double debug_spawndelay = 0;

    public void add(Monster node) {
        if (root == null) {
            root = node;
            root.next = null;
        } else {
            Monster tmp = root;
            while (tmp.next != null) {
                tmp = tmp.next;
            }
            tmp.next = node;
            tmp = tmp.next;
            tmp.next = null;
        }
    }

    void update(Graphics g) {
        Monster temp = root;
        while (temp != null) {
            temp.update(g);
            temp = temp.next;
        }
    }

    void move(double time) {
        debug_spawndelay += time;
        if (size() < 5 && debug_spawndelay > 500) {
            add(new Monster(2000, 1.0, 100));
            debug_spawndelay = 0;
        }
        // TODO insertion sort looking for health (lowest health is first element)
        Monster temp = root;
        while (temp != null) {
            temp.move(time);
            temp = temp.next;
        }
    }

    public int size() {
        if (root == null) {
            return 0;
        } else {
            Monster tmp = root;
            int i = 1;
            while (tmp.next != null) {
                tmp = tmp.next;
                i++;
            }
            return i;
        }
    }

    Monster getRoot() {
        return root;
    }

    public void remove(Monster lowest) {
        Monster tmp = root;
        if (tmp == null) {
            return;
        }
        if (tmp == lowest) {
            root = tmp.next;
            return;
        } else if (tmp.next == null) {
            return;
        }

        while (tmp.next != null && tmp.next != lowest) {
            tmp = tmp.next;
        }
        if (tmp.next != null && tmp.next == lowest) {
            tmp.next = tmp.next.next;
        }
    }
}
